
import json
from flask import Blueprint, jsonify, request
from App.models.db_models import Team, User
from App.models._models import add,save,close, getSingleMa


team = Blueprint('team', __name__, url_prefix="/team")


@team.route('/create', methods=['PUT'])
def team_create():
    classname1 = request.json.get('classname')
    user_name1 = request.json.get('user_name')

    if User.query.filter(User.username == user_name1).first().isTeam != None:
        # 前置条件失败（如执行条件更新时的冲突）
        return jsonify({"code": 412, "msg": "您已有队伍，无法创建"})
    if Team.query.filter(Team.className == classname1).first() != None:
        return jsonify({"code": 412, "msg": "该队伍名已存在"})

    item = Team(className=classname1, leader=user_name1,
                inviteCode=getSingleMa(), peopleNum=1)
    add(item)
    User.query.filter(User.username == user_name1).update(
        {User.isTeam: classname1})
    save()
    close()

    return jsonify({"code": 201, "msg": "创建成功"})        # 如果新资源被创建


@team.route('/join', methods=['PUT'])
def team_join():
    invtecode1 = request.json.get('invtecode')
    user_name1 = request.json.get('user_name')
    if User.query.filter(User.username == user_name1).first().isTeam != None:
        close()
        return jsonify({"code": 401, "msg": "您已有队伍，无法重复加入"})
    theClass = Team.query.filter_by(inviteCode=invtecode1).first()
    if theClass == None:
        close()
        return jsonify({"code": 401, "msg": "邀请码不存在"})
    User.query.filter(User.username == user_name1).update(
        {User.isTeam: theClass.className}, synchronize_session=False)
    theisTeams = User.query.filter_by(
        isTeam=theClass.className).all()
    Team.query.filter(Team.className == theClass.className).update(
        {Team.peopleNum: len(theisTeams)})
    save()
    close()
    return jsonify({"code": 201, "msg": "加入成功"})




@team.route('/refer', methods=['POST'])
def team_refer():
    user_name1 = request.json.get('user_name')
    theuser = User.query.filter_by(username=user_name1).first()
    
    theClass = Team.query.filter(
        Team.className == theuser.isTeam).first()
    if theClass == None:
        return jsonify(  
            {
            "isTeam":False,
            }
        )
    themembers = User.query.filter(
        User.isTeam == theuser.isTeam).all()
    status = "member"
    if theClass.leader == user_name1:
        status = "leader"
    # print(themembers[0])
    # for th in themembers:
    #     print("th=",th)
    #     for tt in th:
    #         print('tt=',tt)
    a = themembers
    # b=[]
    # for user in a:
    #     b[i]=user.username
    #     print(b)
    # print(type(a))

    # b = [user for user in a]
    # print(b)# 从a中的每一行取第一个元素。
    # return 'success'
    
    
    


    json_path = "format.json"
    # 0. 构造数据
    # data = []
    # for i in range(len(themembers)):
    #     data.append({"member": b[i]})
    data = []
    for user in a:
        data.append({"member": user.username})

    # 1.写入 json 文件。其中 'w' 表示覆盖写入
    with open(json_path, 'w') as write_f:
           write_f.write(json.dumps(data, indent=4, ensure_ascii=False))

    # 2.读取 json 日志文件
    with open(json_path, 'r') as load_f:
       data = json.load(load_f)

    # print( data)
    close()
    return jsonify(
        {
            "isTeam":True,
            "team":[{
            "className": theClass.className,
            "inviteCode": theClass.inviteCode,
            "peopleNum": theClass.peopleNum,
            "status":status,
            "member": 
                data
        }]
        }
            

    )
